/* eslint-disable prefer-destructuring,no-await-in-loop */
/**
 * Created by mar105 on 2019-01-08.
 */
import React, { Component } from 'react';
import { Modal, message } from 'antd';
import * as commonUtils from '../../utils/utils'; /* 通用方法 */
import * as commonBusiness from './commonBusiness'; /* 单据业务功能 */
import * as commonServices from '../../services/services'; /*   服务类   */
import * as commonConfig from '../../utils/config';
import * as commonFunc from './commonFunc'; /* 通用单据方法 */

const { confirm } = Modal;

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      // this.state = {
      //   masterConfig: {}, /* 主表配置 */
      //   slaveConfig: {}, /* 从表配置 */
      //   slaveColumn: [], /* 显示的从表表头 */
      //   checkConfig: {}, /* 审核配置 */
      //   checkColumn: [], /* 显示的审核表表头 */
      //
      //   billnosetting: {}, /* 是否自动审核 */
      //   report: [], /* 打印模板 */
      //   masterData: {}, /* 主表数据 */
      //   slaveData: [], /* 从表数据 */
      //   dataTotal: {}, /* 合计字段 */
      //   checkData: [], /* 审核表数据 */
      //   masterFlag: false, /* 是否获取主表数据 */
      //   slaveFlag: false, /* 是否获取从表数据 */
      //   checkFlag: false, /* 是否获取审核表数据 */
      //   sId: '', /* 数据Id */
      //   enabled: false, /* 页面是否可编辑 */
      //   slaveSelectedRowKeys: [], /*   已选择的数据行(数据格式:数组)   */
      //   slaveDelData: [], /*   已删除的数据集合,保存的时候会与从表一并传给服务器(数据格式:数组)   */
      //   expand: false, /* 默认主表只显示2行 */
      //   imgSrc: '', /* Avatar组件中的img中src的资源路径 */
      //   currentIndexFlag: false, /* 默认不显示当前的数据在主表页的位置序号 */
      // };
      this.form = {}; /*   表单对象   */
      const { sModelsId, sModelsType } = props;
      if (sModelsType.includes('cashier/')) {
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sCustomerId', []);
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sCustomerNo', []);
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sCustomerName', []);
      }
    }

    componentWillReceiveProps(nextProps) {
      const {
        formData, currentId, sModelsType, masterData,
      } = nextProps;
      let { slaveColumn } = nextProps;
      if (commonUtils.isEmptyArr(slaveColumn) && formData.length > 0) {
        const sId = currentId !== undefined ? currentId : '';
        /* 数据Id */
        const masterConfig = formData.filter(item => !item.bGrd)[0];
        /* bGrd代表是否是表格 */
        const slaveConfig = formData.filter(item => item.bGrd && item.sTbName !== 'sysbillcheckresult')[0];
        slaveColumn = commonFunc.getHeaderConfig(slaveConfig);
        const checkConfig = formData.filter(item => item.bGrd && item.sTbName === 'sysbillcheckresult')[0];
        const checkColumn = commonFunc.getHeaderConfig(checkConfig);
        let addState = {};
        if (sId === '') {
          const config = {};
          config.masterConfig = masterConfig;
          config.slaveConfig = slaveConfig;
          addState = this.handleAdd(config, nextProps.app.currentPane.copyTo, true);
        } else {
          this.handleGetData(masterConfig, slaveConfig, checkConfig);
        }
        this.props.onSaveState({
          masterConfig, slaveConfig, slaveColumn, checkConfig, checkColumn, sId, pageLoading: false, ...addState,
        });
      }

      // 获取应收款
      if (sModelsType.includes('sales/') || sModelsType.includes('cashier/') || sModelsType.includes('manufacture/')) {
        if (commonUtils.isNotEmptyObject(masterData) && (commonUtils.isEmptyObject(this.props.masterData) || masterData.sCustomerId !== this.props.masterData.sCustomerId)) {
          this.getCustomerReceipt(masterData);
        }
      }
    }

    shouldComponentUpdate(nextProps) {
      const { slaveColumn } = nextProps;
      return commonUtils.isNotEmptyArr(slaveColumn);
    }

    /**   获取应收账款   */
    getCustomerReceipt = async (masterData) => {
      const { sModelsId } = this.props;
      if (!commonUtils.isEmpty(masterData.sCustomerId)) {
        const url = `${commonConfig.server_host}business/getProData?sModelsId=${sModelsId}`;
        const value = { sProName: 'Sp_Receivables_AR', paramsMap: { sStatistics: masterData.sCustomerId } };
        const dataReturn = (await commonServices.postValueService(this.props.app.token, value, url)).data;
        if (dataReturn.code === 1) {
          /*   数据查询成功   */
          const [returnData] = dataReturn.dataset.rows[0].dataSet.outData;
          const masterDataNew = {
            ...masterData,
            dNoReceiptMoney: returnData.dNoReceiptMoney,
            dDueReceiptMoney: returnData.dNoReceiptMoney,
          };
          this.props.onSaveState({ masterData: masterDataNew });
        } else { /*   失败   */
          this.props.getServiceError(dataReturn);
        }
      }
    }

    /**   获取上查下查数据   */
    getSearchUpDownData = async (showConfig) => {
      const { sModelsId } = this.props;
      const url = `${commonConfig.server_host}searchupdown/getSearchUpDown/${showConfig.sId}?sModelsId=${sModelsId}`;
      const conditonValues = this.props.getSqlCondition(showConfig);
      if (commonUtils.isNotEmptyObject(conditonValues)) {
        /*   调用后台接口   */
        const body = {
          sSqlCondition: commonUtils.isEmptyObject(conditonValues) ? '' : conditonValues, /*   查询条件   */
        };
        const dataReturn = (await commonServices.postValueService(this.props.app.token, body, url)).data;
        if (dataReturn.code === 1) {
          /*   数据查询成功   */
          return dataReturn.dataset.rows;
        } else { /*   失败   */
          this.props.getServiceError(dataReturn);
          return [];
        }
      }
    };

    /**   获取主表、从表、审核表数据   */
    handleGetData = (masterConfig, slaveConfig, checkConfig) => {
      const { currentId } = this.props; /* 当前页签数据 */
      const sId = currentId !== undefined ? currentId : '';
      this.props.handleGetDataOne({
        name: 'master', configData: masterConfig, condition: { sId, pageSize: '', pageNum: '' },
      });
      this.props.handleGetDataSet({
        name: 'slave', configData: slaveConfig, condition: { sSqlCondition: { sParentId: sId } },
      });
      this.props.handleGetDataSet({
        name: 'check', configData: checkConfig, condition: { sSqlCondition: { sParentId: sId } },
      });
    };

    /**  点击新增按钮   */
    handleAdd = (config, copyTo, isWait) => {
      /*   外置处理业务   */
      const { sModelsId } = this.props;
      let masterConfig = commonUtils.isEmptyObject(config) ? {} : config.masterConfig;
      if (!isWait) {
        masterConfig = this.props.masterConfig;
      }
      let masterData = commonFunc.getDefaultData(masterConfig);
      masterData.handleType = 'add';
      masterData.sId = commonUtils.createSid();
      masterData.sFormId = sModelsId;
      masterData.maxBillNo = 'sBillNo';
      const slaveData = [];
      // const slaveTotal = [];
      // const tableDataTotal = {};
      if (commonUtils.isNotEmptyObject(copyTo)) {
        const copyToMasterConfig = copyTo.config.filter(item => item.sControlName === copyTo.name);
        const copyToSlaveConfig = copyTo.config.filter(item => item.sControlName.toLowerCase() === `${copyTo.name}.slave`.toLowerCase());
        const masterAssignField = commonUtils.isNotEmptyArr(copyToMasterConfig) ? copyToMasterConfig[0].sAssignField : '';
        const slaveAssignField = commonUtils.isNotEmptyArr(copyToSlaveConfig) ? copyToSlaveConfig[0].sAssignField : '';
        masterData = { ...masterData, ...commonFunc.getAssignFieldValue(masterAssignField, copyTo.masterData) };

        copyTo.slaveData.forEach((item) => {
          const newCopyTo = {};
          newCopyTo.masterData = copyTo.masterData;
          newCopyTo.slaveData = item;
          let tableDataRow = commonFunc.getDefaultData(config.slaveConfig, newCopyTo); // 取默认值
          tableDataRow = { ...tableDataRow, ...commonFunc.getAssignFieldValue(slaveAssignField, item, newCopyTo) }; // 取赋值字段
          tableDataRow.handleType = 'add';
          tableDataRow.sId = commonUtils.createSid();
          tableDataRow.sParentId = masterData.sId;
          slaveData.push(tableDataRow);
        });
      }
      const state = {
        masterData,
        slaveData,
        slaveSelectedRowKeys: [],
        checkData: [],
        checkSelectedRowKeys: [],
        searchUpDownData: {},
        enabled: true,
      };
      if (isWait) {
        return state;
      } else {
        this.props.onSaveState(state);
        return true;
      }
    };

    /**   点击修改按钮操作   */
    handleEdit = () => {
      const { masterConfig, slaveConfig, checkConfig } = this.props;
      this.handleGetData(masterConfig, slaveConfig, checkConfig);
      this.props.onSaveState({ enabled: true });
    };

    /**   表单回带   */
    handleForm = (form) => {
      this.form = form;
    };

    /**   toolbar审核(消审)   */
    handleAudit = (flag) => {
      /*   待用数据声明   */
      const { masterData, gdsformconst } = this.props;
      /*   作废订单不能审核   */
      if (masterData.bInvalid) {
        message.warning(gdsformconst.filter(item => (item.sName === 'sToVoid'))[0].showName);
        return '';
      }
      /**   数据审核   */
      this.dataAudit(flag);
    };

    /**   数据审核   */
    dataAudit = async (flag) => {
      /*   待用数据声明   */
      const {
        sModelsId, sModelsType, masterData, app, masterConfig, slaveConfig, checkConfig, slaveData,
      } = this.props;
      const bGetProductIdDropDown = slaveData.findIndex(item => !commonUtils.isEmpty(item.sProductInfo)) > -1;
      /*   数据参数   */
      const value = {
        sClientType: '1',
        paramsMap: {
          iFlag: flag, iTmpCheck: 0, sFormGuid: sModelsId, sGuid: masterData.sId,
        },
      };
      /*   数据审核   */
      const url = `${commonConfig.server_host}business/doExamine?sModelsId=${sModelsId}`;
      const returnData = (await commonServices.postValueService(app.token, value, url)).data;
      /*   接收返回值   */
      /*   成功的话刷新页面(同步主表和从表数据),不成功就弹出错误提示   */
      if (returnData.code === 1) { /*   成功   */
        /*   flag审核是1,消审是0   */
        /*   弹出提示   */
        message.success(returnData.msg);
        /*   设置state   */
        if (sModelsType.includes('sales/') && bGetProductIdDropDown) {
          commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductId', []);
        }
        this.handleGetData(masterConfig, slaveConfig, checkConfig);
        /*  审核(消审)后刷新跳转路由数据（commonList）的数据 */
        if (this.props.app.currentPane.refresh !== undefined) {
          this.props.app.currentPane.refresh();
        }
      } else { /*   失败   */
        this.props.getServiceError(returnData);
      }
    };

    /**   toolbar保存   */
    handleSaveData = async (params) => {
      const {
        token, sModelsId, masterData, masterConfig, slaveConfig, checkConfig, billnosetting,
      } = this.props;
      const returnData = await commonBusiness.saveData({ token, value: params, sModelsId });
      if (commonUtils.isNotEmptyObject(returnData)) {
        this.props.onSaveState({
          enabled: false, currentId: masterData.sId,
        });
        if (billnosetting.bAutoCheck) {
          this.handleAudit(1);
        } else {
          this.handleGetData(masterConfig, slaveConfig, checkConfig);
          if (this.props.app.currentPane.refresh !== undefined) {
            this.props.app.currentPane.refresh();
          }
        }
        return true;
      } else {
        return false;
      }
    };
    /**   toolbar校验保存   */
    handleValidateSave = () => {
      this.form.validateFieldsAndScroll((err) => {
        /*   验证通过与不通过走不同的流程   */
        const arr = document.getElementById('saleAddForm').getElementsByTagName('label');
        const addArr = document.getElementById('saleAddForm').getElementsByClassName('ant-form-item-control-wrapper');
        if (err) { /*   验证失败   */
          /*   直接渲染显示错误提示   */
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].getAttribute('class') === 'ant-form-item-required') {
              if (Object.keys(err).indexOf(arr[i].getAttribute('for')) > -1) {
                let newP = document.createElement('p');
                newP.style.color = 'red';
                newP.style.fontSize = 10;
                newP.innerHTML = arr[i].title + '为必填项';
                addArr[i].getElementsByTagName('p').length ? null : addArr[i].appendChild(newP);
              } else {
                addArr[i].getElementsByTagName('p').length ? addArr[i].removeChild(addArr[i].getElementsByTagName('p')[0]) : null;
              }
            }
          }
          // for (const key of Object.keys(err)) {
          //   message.error(err[key].errors[0].message);
          // }
        } else { /*   验证成功   */
          for (let i = 0; i < arr.length; i++) {
            addArr[i].getElementsByTagName('p').length ? addArr[i].removeChild(addArr[i].getElementsByTagName('p')[0]) : null;
          }
          const {
            masterConfig, masterData, slaveConfig, slaveData, slaveDelData, app,
          } = this.props;
          if (commonUtils.isEmptyArr(slaveData)) {
            message.error(commonFunc.showMessage(app.commonConst, 'slaveNotNull')); // 从表不能为空！
            return;
          }
          if (!commonBusiness.validateTable(slaveConfig, slaveData)) {
            return;
          }
          const data = [];
          data.push(commonBusiness.mergeData('master', masterConfig.sTbName, [masterData]));
          data.push(commonBusiness.mergeData('slave', slaveConfig.sTbName, slaveData, slaveDelData));
          this.handleSaveData({ data, sClientType: '1' });
        }
      });
    };

    /* 切换作废状态 */
    handleOkChangeInvaild = async (props) => {
      const {
        sModelsId, masterData, masterConfig, handleType,
      } = props;
      const value = {
        sClientType: '1',
        sId: [masterData.sId],
        sTableName: masterConfig.sTbName,
        handleType,
      };
      const url = `${commonConfig.server_host}checkModel/updatebInvalid?sModelsId=${sModelsId}`;
      const { data } = await commonServices.postValueService(props.app.token, value, url);
      if (data.code === 1) {
        message.success(data.msg);
        masterData.bInvalid = handleType === 'toVoid'; /* 作废状态 */
        this.props.onSaveState({ masterData });
        /*  审核(消审)后刷新跳转路由数据（commonList）的数据 */
        props.app.currentPane.refresh();
      } else {
        this.props.getServiceError(data);
      }
    };

    /* 作废、取消作废的公用函数 */
    handleInvalid = (obj) => {
      const props = { ...this.props, ...this.state, ...obj };
      const onOkInvaild = this.handleOkChangeInvaild;
      confirm({
        title: obj.title,
        onOk() {
          onOkInvaild(props);
        },
        onCancel() {
        },
      });
    };

    /*   单据页上查下查跳转页面   */
    handleSearchUpDown = async (sId, sActiveId) => {
      /*   待用数据声明   */
      const { dispatch, sTabId } = this.props;
      dispatch({
        type: 'content/onRouter',
        payload: {
          url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
          sParentId: sTabId, /*   父页面编号   */
          checkedId: sId,
        },
      });
    };

    /*   上查下查三级菜单  在上一条下一条时必须清除searchUpDownData  */
    handleSearchUpDownThird = async (upDownKey) => {
      /*   待用数据声明   */
      const { masterConfig } = this.props;
      let { searchUpDownData } = this.props;
      /**   获取sqlCondition参数：{sSqlCondition,sId}   */
      searchUpDownData = commonUtils.isEmptyObject(searchUpDownData) ? {} : searchUpDownData;
      if (commonUtils.isNotEmptyObject(masterConfig) && commonUtils.isEmptyObject(searchUpDownData)) {
        const searchUpDownConfig = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(`${upDownKey}.`));
        for (const item of searchUpDownConfig) {
          searchUpDownData[item.sControlName] = await this.getSearchUpDownData(item);
        }
        this.props.onSaveState({ searchUpDownData });
      }
    };

    /*   单据页复制到   */
    handleCopyTo = (name, sActiveId) => {
      /*   待用数据声明   */
      const {
        dispatch, masterConfig, masterData, slaveData,
      } = this.props;
      const copyTo = {};
      const copyToConfig = masterConfig.gdsconfigformslave.filter(item => item.sControlName.includes(name));
      copyTo.name = name;
      copyTo.config = copyToConfig;
      copyTo.masterData = masterData;
      copyTo.slaveData = slaveData;
      dispatch({
        type: 'content/onRouter',
        payload: {
          url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
          copyTo,
        },
      });
    };

    /*  上一条、下一条、首条、末条 */
    handleSearchData = async (handleType) => {
      const {
        sModelsId, app, currentIndexFlag, currentPageNo,
      } = this.props;
      const { currentPane, token } = app;
      const {
        pages, sFilterOrderBy, bFilter, sListFormmasterId, currentIndex,
      } = currentPane;
      let currentPosition = currentIndexFlag ? currentPageNo : (((pages.current - 1) * commonConfig.pageSize) + Number.parseInt(currentIndex, 10)) + 1;
      if (handleType === 'first') {
        currentPosition = 1;
      } else if (handleType === 'end') {
        currentPosition = pages.total;
      }
      if (!commonUtils.isNum(currentPosition)) { // 如果是列表直接点增加，就跳到第一条去
        currentPosition = 1;
      }

      const value = {
        sClientType: '1', sFilterOrderBy, bFilter, sListFormmasterId, currentPosition, handleType, iCountSum: pages.total,
      };
      const url = `${commonConfig.server_host}business/getBusinessDataByIndex?sModelsId=${sModelsId}`;
      /*   接收返回值   */
      const { data } = await commonServices.postValueService(token, value, url);
      /*   接收返回值   */
      /*   成功的话刷新页面(同步主表和从表数据),不成功就弹出错误提示   */
      if (data.code === 1) {
        /*   数据查询成功   */
        const returnData = data.dataset.rows[0];
        const { masterConfig, slaveConfig, checkConfig } = this.props;
        this.props.onSaveState({
          currentIndexFlag: true,
          currentPageNo: returnData.currentPosition,
          currentId: returnData.sId,
          searchUpDownData: {},
          slaveSelectedRowKeys: [],
        });
        this.handleGetData(masterConfig, slaveConfig, checkConfig);
        return true;
      } else { /*   失败   */
        this.props.getServiceError(data);
        return false;
      }
    };

    /*   取消操作  */
    handleCancel = (obj) => {
      /*   待用数据声明   */
      const { masterConfig, slaveConfig, checkConfig } = this.props;
      const onGetDataOk = this.handleGetData;
      const onSaveStateOk = this.props.onSaveState;
      confirm({
        title: obj.title,
        onOk() {
          onGetDataOk(masterConfig, slaveConfig, checkConfig);
          onSaveStateOk({ enabled: false });
        },
        onCancel() {
        },
      });
    };

    /* 删除 */
    handleDel = (obj) => {
      const props = { ...this.props, ...this.state };
      const onOkDel = this.handleOkDel;
      confirm({
        title: obj.title,
        onOk() {
          onOkDel(props);
        },
        onCancel() {
        },
      });
    };

    /* 确定要删除 */
    handleOkDel = async (props) => {
      /*   数据参数   */
      const {
        token, sModelsId, masterConfig, masterData, slaveConfig, checkConfig,
      } = props;
      const value = {
        sClientType: '1',
        data: {
          sMasterTable: masterConfig.sTbName,
          sId: [masterData.sId],
          sSlaveTable: [
            {
              tableName: slaveConfig.sTbName,
              relationName: 'sParentId',
            }, {
              tableName: checkConfig.sTbName,
              relationName: 'sBillId',
            }],
        },
      };
      const url = `${commonConfig.server_host}business/delMasSlaBusinessData?sModelsId=${sModelsId}`;
      /*   接收返回值   */
      const { data } = await commonServices.postValueService(token, value, url);
      if (data.code === 1) {
        /*   数据删除成功   */
        if (this.props.app.currentPane.refresh !== undefined) {
          this.props.app.currentPane.refresh();
        }
        this.handleDelDataSuccess(props);
      } else { /*   失败   */
        this.props.getServiceError(data);
      }
    };

    /* 数据删除成功跳转到新路由即pane */
    handleDelDataSuccess = (props) => {
      const { app } = props;
      let { panes, currentPane } = app;
      /* 删除单据后退出当前路由后,标签panes变化后的集合 */
      panes = panes.filter(pane => pane.key !== currentPane.key);
      /* 跳转到panes集合的最后一个路由，因为panes集合一定含有主页路由所以panes的集合大于等于1 */
      currentPane = panes[panes.length - 1];
      this.props.onRemovePane(panes, currentPane);
    };

    /**   添加表格空行   */
    handleTableAdd = (name, isWait) => {
      /*   从CommonBase获取默认参数   */
      const {
        [`${name}Data`]: tableData, masterData, masterConfig, sModelsType, gdsformconst,
      } = this.props;
      let tableDataRow = this.props.onDataRowAdd(name, true);
      /*   添加行的业务处理拿出去   */
      if (sModelsType.includes('sales/')) {
        if (commonUtils.isEmptyStr(masterData.sCustomerId)) {
          const iIndex = masterConfig.gdsconfigformslave.findIndex(item => (item.sName === 'sCustomerId' && item.bVisible));
          if (iIndex > -1) {
            const { showName } = masterConfig.gdsconfigformslave[iIndex];
            message.warn(showName + commonFunc.showMessage(gdsformconst, 'isNotNull')); // 不能为空
            tableDataRow = {};
          }
        }
      }

      if (isWait) {
        return tableDataRow;
      } else if (commonUtils.isNotEmptyObject(tableDataRow)) {
        tableData.push(tableDataRow);
        this.props.onSaveState({ [`${name}Data`]: tableData, [`${name}Pagination`]: { total: tableData.length, current: 9999 } });
      }
    };

    /** 表格数据更改 */
    // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
    handleTableChange = async (name, sFieldName, changeValue, sId, dropDownData) => {
      /*   从CommonBase获取默认参数   */
      const {
        [`${name}Data`]: tableData, masterData, sModelsType, sModelsId, token, app,
      } = this.props;
      let {
        employeeData,
      } = this.props;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      if (sFieldName.substring(0, 1) === 'd' && commonUtils.convertToNum(tableData[iIndex][sFieldName]) === commonUtils.convertToNum(changeValue[sFieldName])) return;

      let tableDataRow = this.props.onDataChange(name, sFieldName, changeValue, sId, dropDownData, true);
      if ((sFieldName === 'sProductId' || sFieldName === 'sProductName' || sFieldName === 'sProductStyle' || sFieldName === 'sProductUnit' || sFieldName === 'sProductNo'
        || sFieldName === 'sCustomerMaterialNo' || sFieldName === 'sProductParentId') && !commonUtils.isEmpty(tableDataRow.sProductId)) {
        const productIdDropDown = commonUtils.getStoreDropDownData(sModelsId, 'slave', 'sProductId');
        const iProductIdIndex = productIdDropDown.findIndex(item => item.sId === tableDataRow.sProductId);
        if (iProductIdIndex === -1) {
          tableDataRow.sProductInfo = JSON.stringify({
            sProductName: tableDataRow.sProductId,
            sProductStyle: tableDataRow.sProductStyle,
            sProductUnit: tableDataRow.sProductUnit,
            sProductNo: tableDataRow.sProductNo,
            sCustomerMaterialNo: tableDataRow.sCustomerMaterialNo,
            sProductParentId: tableDataRow.sProductParentId,
          });
        }
      }
      if (sFieldName === 'sTeamName') {
        const sTeamId = tableData[iIndex].sTeamId;
        const sSlaveId = tableData[iIndex].sId;
        const sParentId = tableData[iIndex].sParentId;
        const url = `${commonConfig.server_host}eleteamemployee/getEleteamemployee?sModelsId=${sModelsId}&sTeamId=${sTeamId}&sSlaveId=${sSlaveId}&sParentId=${sParentId}`;
        const dataReturn = (await commonServices.getService(token, url)).data;
        if (dataReturn.code === 1) {
          const returnData = dataReturn.dataset.rows;
          const employeeDataNew = employeeData.filter(item => item.sSlaveId !== sId);
          const employeeSlaveData = [];
          returnData.forEach((child) => {
            employeeSlaveData.push({
              sId: child.sId,
              sParentId: child.sParentId,
              sSlaveId: child.sSlaveId,
              sEmployeeId: child.sEmployeeId,
              handleType: 'add',
            });
          });
          employeeData = employeeDataNew.concat(employeeSlaveData);
        }
      }
      /* 各种金额，税额，价格计算 */
      const models = sModelsType.includes('sales/') || sModelsType.includes('manufacture/') ? 'Product' : 'Materials';
      if (sModelsType.includes('purchase/') || sModelsType.includes('materialsStock/') || sModelsType.includes('outside/')) {
        const { sComputeId, sConversionComputeId, sReConversionComputeId } = tableDataRow;
        if (sFieldName === 'dAuxiliaryQty' || sFieldName === 'sMaterialsStyle') {
          if (commonUtils.isEmpty(sComputeId)) {
            tableDataRow = commonBusiness.getMaterialsQty(app, tableDataRow);
          } else {
            tableDataRow.dMaterialsQty = await commonBusiness.getFormulaValue({
              token, sModelsId, masterData, tableDataRow, sComputeId,
            });
          }
          if (!commonUtils.isEmpty(sConversionComputeId)) {
            tableDataRow.dConversionQty = await commonBusiness.getFormulaValue({
              token, sModelsId, masterData, tableDataRow, sConversionComputeId,
            });
          }
        } else if (sFieldName === 'dMaterialsQty') {
          const { sReComputeId } = tableDataRow;
          if (commonUtils.isEmpty(sReComputeId)) {
            tableDataRow = commonBusiness.getAuxiliaryQty(app, tableDataRow);
          } else {
            tableDataRow.dAuxiliaryQty = await commonBusiness.getFormulaValue({
              token, sModelsId, masterData, tableDataRow, sComputeId: sReComputeId,
            });
          }
          if (!commonUtils.isEmpty(sReConversionComputeId)) {
            tableDataRow.dConversionQty = await commonBusiness.getFormulaValue({
              token, sModelsId, masterData, tableDataRow, sReConversionComputeId,
            });
          }
        }
      }
      tableDataRow = commonBusiness.getCalculateAllMoney(app, models, sFieldName, masterData, tableDataRow);
      tableData[iIndex] = tableDataRow;
      if (sFieldName === 'dProcessQty' || sFieldName === 'sWageId') {
        const dProcessQty = tableData[iIndex].dProcessQty;
        const sWageId = tableData[iIndex].sWageId;
        const resultValue = { dProcessQty, sWageId };
        const value = {
          handleType: 'getResult',
          replaceData: { /* 数据列集合Map形式 */
            billSlave: resultValue, /* 单据从表 */
          },
          sFormulaId: sWageId, /* 计算公式ID */
          sClientType: '1',
        };
        const url = `${commonConfig.server_host}replaceField/checkReplaceField?sModelsId=${sModelsId}`;
        const { data } = await commonServices.postValueService(token, value, url);
        if (data.code === 1) {
          tableData[iIndex].dWageMoney = data.dataset.rows[0].sResult;
          const dWageMoneyTotal = tableData[iIndex].dWageMoney;
          if (commonUtils.isNotEmptyNumber(dWageMoneyTotal)) {
            let dProportionTotal = 0;
            const employeeSlaveData = employeeData.filter(item => item.sSlaveId === sId);
            employeeSlaveData.forEach((item) => {
              if (commonUtils.isNotEmptyNumber(item.dProportion)) {
                dProportionTotal += item.dProportion;
              }
            });
            employeeSlaveData.forEach((item) => {
              if (commonUtils.isNotEmptyNumber(item.dProportion)) {
                item.dWageMoney = (item.dProportion / dProportionTotal) * dWageMoneyTotal;
                item.handleType = commonUtils.isEmpty(item.handleType) ? 'update' : item.handleType;
              }
            });
          }
        } else { /*   失败   */
          this.props.getServiceError(data);
        }
      }
      this.props.onSaveState({ [`${name}Data`]: tableData, employeeData });
    };

    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      const {
        sModelsId, sModelsType, slaveData, app, masterConfig,
      } = this.props;
      if (sFieldName === 'sCustomerId') {
        if (commonUtils.isNotEmptyArr(slaveData)) {
          // 从表有数据，请删除后修改客户！
          message.warn(commonFunc.showMessage(app.commonConst, 'slaveHasDataPleaseDel'));
          return;
        }
        commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductId', []);
        commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductNo', []);
        commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sProductName', []);
      } else if (sFieldName === 'sWareHouseId') {
        commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sMaterialsId', []);
        commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sMaterialsNo', []);
        commonUtils.setStoreDropDownData(sModelsId, 'slave', 'sMaterialsName', []);
      } else if (sModelsType.includes('cashier/') && sFieldName === 'sBillType') {
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sCustomerId', []);
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sCustomerNo', []);
        commonUtils.setStoreDropDownData(sModelsId, 'master', 'sCustomerName', []);
        changeValue.sCustomerId = '';
        const iIndex = masterConfig.gdsconfigformslave.findIndex(item => item.sName === 'sCustomerId');
        if (iIndex > -1) {
          masterConfig.gdsconfigformslave[iIndex].bReGetDropDown = true;
        }
        this.props.onSaveState({ masterConfig });
      }
      const returnData = this.props.onChange(name, sFieldName, changeValue, sId, dropDownData, isWait);
      if (sFieldName === 'sWareHouseId' || sFieldName === 'tDeliverDate') {
        const slaveDataNew = [];
        slaveData.forEach((item) => {
          slaveDataNew.push({ ...item, [sFieldName]: changeValue[sFieldName] });
        });
        this.props.onSaveState({ slaveData: slaveDataNew });
      }
      return returnData;
    }

    handleBtnPrint = (sActiveId) => {
      const {
        app, sModelsId, masterConfig, masterData, slaveConfig,
      } = this.props;
      const { token } = app;
      const queryFilter = {};
      queryFilter[masterConfig.sId] = { sId: masterData.sId };
      queryFilter[slaveConfig.sId] = { sSqlCondition: { sParentId: masterData.sId } };
      const queryFilterJson = escape(JSON.stringify(queryFilter));
      const urlPrint = `${commonConfig.server_host}printReport/printPdf/${sActiveId}?queryFilter=${queryFilterJson}&sModelsId=${sModelsId}&sMaintableId=${masterConfig.sId}&token=${encodeURIComponent(token)}`;
      window.open(urlPrint);
    }

    handleTitleChange = (slavePagination) => {
      this.props.onSaveState({ slavePagination });
    };

    render() {
      const { masterData } = this.props;
      const imgSrc = commonBusiness.handleAddIcon(masterData);
      return (
        <ChildComponent
          {...this.props}
          {...this.state}
          onAdd={this.handleAdd}
          onEdit={this.handleEdit}
          onSubmit={this.handleValidateSave}
          onSaveData={this.handleSaveData}
          onSelectRowChange={this.handleSelectRowChange}
          onReturnForm={this.handleForm}
          onChangeInvalid={this.handleInvalid}
          onBtnExamine={this.handleAudit.bind(this, 1)}
          onBtnCancelExamine={this.handleAudit.bind(this, 0)}
          onCopyTo={this.handleCopyTo}
          onSearchData={this.handleSearchData}
          onNext={this.handleSearchData.bind(this, 'next')}
          onBtnPrior={this.handleSearchData.bind(this, 'up')}
          onBtnFirst={this.handleSearchData.bind(this, 'first')}
          onBtnLast={this.handleSearchData.bind(this, 'end')}
          onSearchUpDown={this.handleSearchUpDown}
          onGetData={this.handleGetData}
          onCancel={this.handleCancel}
          onDel={this.handleDel}
          onSearchUpDownThird={this.handleSearchUpDownThird}
          onDataRowAdd={this.handleTableAdd}
          onDataChange={this.handleTableChange}
          onBtnPrint={this.handleBtnPrint}
          onChange={this.handleMasterChange}
          onTitleChange={this.handleTitleChange}
          imgSrc={imgSrc}
        />
      );
    }
  };
};
